<template>
  <div class="pages">
    <!-- 头部导航 -->
		<div class="header animate__fadeInDown">
			<button class="back-button fff" @click="router.back()">
				<span class="back-icon">←</span>
			</button>
			<span class="header-title fff">{{routerTitle}}设置</span>
		</div>
    <div class="control-pages">
      <!-- 话术间隔时长 -->
      <div class="content animate__fadeInUp" v-if="routerName === 'interval'">
        <div class="title">话术间隔时长</div>
        <div class="sub-title">默认0.2-0.3秒，可按直播习惯改成合适的参数</div>
        <div class="items">
          <div class="input-block">
            <input type="text" v-model="mainTxtSpace0" placeholder="0.2"/>
            <div class="unit">秒</div>
          </div>
          <div class="symbol">至</div>
          <div class="input-block">
            <input type="text" v-model="mainTxtSpace1" placeholder="0.3"/>
            <div class="unit">秒</div>
          </div>
        </div>
      </div>
      <!-- 点赞感谢 -->
      <div class="content animate__fadeInUp" v-if="routerName === 'upvote'">
        <div class="title">点赞感谢</div>
        <div class="sub-title">默认60秒，可按直播习惯改成合适的参数</div>
        <div class="input-block-one">
          <input type="text" v-model="form.likeTxtSpace" placeholder="60"/>
          <div class="unit">秒</div>
        </div>
        <div class="title">内容设置</div>
        <div style="height: 8px;"></div>
        <textarea placeholder-style="color: #595959;" v-model="likeTxtText" class="textarea" maxlength="-1" placeholder="请输入内容"></textarea>
      </div>
      <!-- 关注感谢 -->
      <div class="content animate__fadeInUp" v-if="routerName === 'attention'">
        <div class="title">关注感谢</div>
        <div class="sub-title">默认15秒，可按直播习惯改成合适的参数</div>
        <div class="input-block-one">
          <input type="text" v-model="form.loveTxtSpace" placeholder="15"/>
          <div class="unit">秒</div>
        </div>
        <div class="title">内容设置</div>
        <div style="height: 8px;"></div>
        <textarea placeholder-style="color: #595959;" v-model="loveTxtText" class="textarea" maxlength="-1" placeholder="请输入内容"></textarea>
      </div>
      <!-- 礼物感谢 -->
      <div class="content animate__fadeInUp" v-if="routerName === 'gift'">
        <div class="title">礼物感谢</div>
        <div class="sub-title">默认30秒，可按直播习惯改成合适的参数</div>
        <div class="input-block-one">
          <input type="text" v-model="form.giftTxtSpace" placeholder="30"/>
          <div class="unit">秒</div>
        </div>
        <div class="title">内容设置</div>
        <div style="height: 8px;"></div>
        <textarea placeholder-style="color: #595959;" v-model="giftTxtText" class="textarea" maxlength="-1" placeholder="请输入内容"></textarea>
      </div>
      <!-- 欢迎话术 -->
      <div class="content animate__fadeInUp" v-if="routerName === 'greet'">
        <div class="title">欢迎话术</div>
        <div class="sub-title">默认30秒，可按直播习惯改成合适的参数</div>
        <div class="input-block-one">
          <input type="text" v-model="form.welcomeSpace" placeholder="30"/>
          <div class="unit">秒</div>
        </div>
        <div class="title">内容设置</div>
        <div style="height: 8px;"></div>
        <textarea placeholder-style="color: #595959;" v-model="welcomeTxtText" class="textarea" maxlength="-1" placeholder="请输入内容"></textarea>
      </div>
      <!-- DeepSeek触发时长 -->
      <div class="content animate__fadeInUp" v-if="routerName === 'deepseekInterval'">
        <div class="title">DeepSeek触发时长</div>
        <div class="sub-title">默认2秒，可按直播习惯改成合适的参数</div>
        <div class="input-block-one">
          <input type="text" v-model="form.dsSpace" placeholder="2"/>
          <div class="unit">秒</div>
        </div>
      </div>
      <div style="height: 57px;"></div>
      <div class="btn-block">
        <button class="live-btn position" @click="submitChanges">保存修改</button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue'
import { dialog } from '@/utils/dialog'
import { useStore } from '@/stores/data'
import { useRouter, useRoute } from 'vue-router';

const router = useRouter();
const store = useStore()


// 使用query参数
const routerName = ref(useRoute().query.name)
const routerTitle = ref(useRoute().query.title)

// 本地表单（直接拷贝后端对象）
const form = reactive<any>({})
// 原始快照（用于 diff）
const original = ref<any>({})

// 文本缓冲区：main 一个整篇；其余 *Txt 用“每行一个”的多行框
const mainTxtRaw = ref('')           // 显示为一整篇话
const giftTxtText = ref('')          // 每行一个 item
const likeTxtText = ref('')
const loveTxtText = ref('')
const welcomeTxtText = ref('')

// mainTxtSpace 两个输入框（区间）
const mainTxtSpace0 = ref<number | string>('')
const mainTxtSpace1 = ref<number | string>('')

// 深拷贝
const cloneDeep = (obj: any) => JSON.parse(JSON.stringify(obj))

// 初始化
onMounted(async () => {
  await store.getConfig()
  initForm()
})

function initForm() {
  const src = cloneDeep(store.userConfig || {})
  Object.keys(src).forEach(k => (form[k] = src[k]))
  original.value = cloneDeep(src)

  // mainTxt：把数组拼成一整篇话（不加分隔，直接连起来）
  mainTxtRaw.value = Array.isArray(form.mainTxt) ? form.mainTxt.join('') : (form.mainTxt || '')

  // 其他 *Txt：按“每行一个”展示
  giftTxtText.value    = Array.isArray(form.giftTxt)    ? form.giftTxt.join('\n')    : ''
  likeTxtText.value    = Array.isArray(form.likeTxt)    ? form.likeTxt.join('\n')    : ''
  loveTxtText.value    = Array.isArray(form.loveTxt)    ? form.loveTxt.join('\n')    : ''
  welcomeTxtText.value = Array.isArray(form.welcometxt) ? form.welcometxt.join('\n') : ''

  // mainTxtSpace：固定两格
  if (Array.isArray(form.mainTxtSpace) && form.mainTxtSpace.length >= 2) {
    mainTxtSpace0.value = form.mainTxtSpace[0]
    mainTxtSpace1.value = form.mainTxtSpace[1]
  } else {
    // 没有则给默认值
    mainTxtSpace0.value = 0.2
    mainTxtSpace1.value = 0.3
  }
}

// ============ 提交前的转换逻辑 ============

// 你的切分逻辑（主话术 mainTxt 专用）
function buildMainTxtBySentenceMerge(text: string): string[] {
  // 1) 按换行切段，去空行
  const lines = (text || '')
    .split('\n')
    .map(s => s.trim())
    .filter(s => s !== '')

  // 2) 每段再按。！？切句
  let sentences: string[] = []
  const re = /[^。！？]+[。！？]+|[^。！？]+$/g
  lines.forEach(line => {
    const parts = line.match(re)
    if (parts) sentences.push(...parts)
    else sentences.push(line)
  })

  // 3) 过滤空与少于两个字
  sentences = sentences.filter(s => {
    const t = s.trim()
    return t !== '' && t.length >= 2
  })

  // 4) 合并：不足 50 字向后追加
  const combined: string[] = []
  let tmp = ''
  for (let i = 0; i < sentences.length; i++) {
    tmp += sentences[i]
    if (tmp.length >= 50) {
      combined.push(tmp)
      tmp = ''
    }
  }
  if (tmp) combined.push(tmp)

  return combined
}

// 通用：每行一个 item（过滤空行，去两端空格）
function splitLines(text: string): string[] {
  return (text || '')
    .split('\n')
    .map(s => s.trim())
    .filter(s => s !== '')
}

// 仅提交变化字段
function isEqual(a: any, b: any) {
  return JSON.stringify(a) === JSON.stringify(b)
}

function diffObject(curr: any, base: any) {
  const out: any = {}
  const keys = new Set([...Object.keys(curr || {}), ...Object.keys(base || {})])
  keys.forEach(k => {
    if (!isEqual(curr[k], base[k])) out[k] = curr[k]
  })
  return out
}

async function submitChanges() {
  // 先构造“提交时的规范对象”（对 *Txt / mainTxt / mainTxtSpace 执行转换）
  const current = cloneDeep(form)

  // mainTxtSpace：强制写回两个数
  const n0 = Number(mainTxtSpace0.value)
  const n1 = Number(mainTxtSpace1.value)
  current.mainTxtSpace = [
    isNaN(n0) ? 0 : n0,
    isNaN(n1) ? 0 : n1,
  ]

  // mainTxt：用“句子切分 + 合并≥50字”规则
  current.mainTxt = buildMainTxtBySentenceMerge(mainTxtRaw.value)

  // 其他 *Txt：每行一个
  current.giftTxt    = splitLines(giftTxtText.value)
  current.likeTxt    = splitLines(likeTxtText.value)
  current.loveTxt    = splitLines(loveTxtText.value)
  current.welcometxt = splitLines(welcomeTxtText.value)

  // 只提交有变化的字段
  const changes = diffObject(current, original.value)
  if (Object.keys(changes).length === 0) {
    // dialog.alert({message: '没有改动需要提交'});
    router.back()
    return
  }

  try {
    await store.updateConfig(changes)
    // 刷新基线
    Object.keys(current).forEach(k => (form[k] = current[k]))
    original.value = cloneDeep(current)
    dialog.alert({ iconType: 'sc', message: '已提交修改'}).then(() => {
      router.back()
    });
  } catch (e: any) {
    console.error(e)
    dialog.alert({message: e?.message || '提交失败'});
  }
}
</script>

<style lang="scss" scoped>
@import './config.scss';
</style>